﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Dao;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Model.ViewModel;
using DeHeng_Mes.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace DeHeng_Mes.Thread
{
    public class MesDataPush
    {
        OrderDao orderDao = new OrderDao();
        ViewDao viewDao = new ViewDao();

        public async Task pushTask()
        {
            Tools.ProduceLogText("Mes数据推送线程启动成功！");

            while (true)
            {
                await Task.Delay(5000);

                try
                {
                    // 查询工单绑定的工件码
                    List<OrderTrace> orderTraces = await orderDao.QueryOrderTrace();

                    if (orderTraces?.Count > 0)
                    {
                        foreach (var orderTrace in orderTraces)
                        {
                            string code = Tools.GetHashCodeFromPushMes(orderTrace.OrderId, orderTrace.TraceId, orderTrace.CreateTime);

                            if (orderTrace.PartPushStatus.Equals("0"))
                            {
                                int partCount = 1;

                                string dataDtlId = Tools.GetHashCodeFromPushMes(orderTrace.TraceId, partCount.ToString(), orderTrace.CreateTime);

                                // 推送单件上件绑定数据
                                int count = await viewDao.PushPartData(new LineMesData()
                                {
                                    OrderId = orderTrace.OrderId,
                                    TraceId = orderTrace.TraceId,
                                    CreateTime = orderTrace.CreateTime,
                                    DataFrom = "德恒W03左右门槛线",
                                    DataId = code,
                                });

                                if (count > 0)
                                {
                                    await orderDao.UpdatePartPushStatus(orderTrace.OrderId, orderTrace.TraceId);
                                }

                            }
                            else if (orderTrace.StationPushStatus.Equals("0"))
                            {
                                int traceId = orderDao.GetCodeId(orderTrace.TraceId);

                                List<int> processIds = null;

                                // 初始化过站信息列表
                                Dictionary<int, PartProcess> partProcesses = new Dictionary<int, PartProcess>();

                                // 初始化投料列表
                                List<CodeBatchCode> codeBatchCodes = new List<CodeBatchCode>();

                                if (traceId > 0)
                                {
                                    processIds = await orderDao.GetProcessIds(traceId);

                                    if (processIds?.Count > 0)
                                    {
                                        foreach (var processId in processIds)
                                        {
                                            PartProcess partProcess = await orderDao.GetProcessData(processId);

                                            if (partProcess == null)
                                                continue;

                                            partProcesses.Add(processId, partProcess);
                                        }
                                    }
                                }

                                // 获取产生投料表
                                codeBatchCodes = await orderDao.GetBtachCodeList(traceId);

                                try
                                {
                                    if (partProcesses?.Count > 0)
                                    {
                                        // 推送数据
                                        foreach (var partProcess in partProcesses)
                                        {
                                            // 获取工站对应工序
                                            string operations = MappingTable.GetOperationId(partProcess.Value.Station);

                                            string stationCode = Tools.GetHashCodeFromPushMes(orderTrace.TraceId, partProcess.Value.Station, partProcess.Value.EndTime);

                                            // 拼接过站数据进行推送
                                            int stationDataRecord = await viewDao.PushStationData(new LineMesDataTrace()
                                            {
                                                DataId = code,
                                                DataTraceId = stationCode,
                                                Station = partProcess.Value.Station,
                                                Process = operations,
                                                Result = partProcess.Value.Result,
                                                CreateTime = partProcess.Value.EndTime,
                                                StartTime = partProcess.Value.StartTime,
                                                EndTime = partProcess.Value.EndTime,
                                                DataFrom = "德恒W03左右门槛线",
                                                UserId = "",
                                            });

                                            // 投料推送
                                            foreach (var codeBatchCode in codeBatchCodes)
                                            {
                                                if (partProcess.Value.Station.Equals(codeBatchCode.Station))
                                                {
                                                    // 获取批次码
                                                    string batchCode = await orderDao.GetBatchCode(codeBatchCode.BatchId);

                                                    string dataDtlId = Tools.GetHashCodeFromPushMes(batchCode, codeBatchCode.BatchCount.ToString(), partProcess.Value.EndTime);

                                                    await viewDao.PushBatchData(new LineMesDataDtl()
                                                    {
                                                        DataId = code,
                                                        DataDtlId = dataDtlId,
                                                        CreateTime = partProcess.Value.EndTime,
                                                        BatchId = batchCode,
                                                        Count = codeBatchCode.BatchCount,
                                                        ProcessId = operations,
                                                        DataFrom = "德恒W03左右门槛线",
                                                    });
                                                }
                                            }

                                            if (partProcess.Value.Station.Equals(SystemConstant.OP10L) || partProcess.Value.Station.Equals(SystemConstant.OP10R))
                                            {
                                                // 获取单件批次
                                                string batch = orderDao.QueryTraceBatch(orderTrace.TraceId);

                                                await viewDao.PushBatchData(new LineMesDataDtl()
                                                {
                                                    DataId = code,
                                                    DataDtlId = Tools.GetHashCodeFromPushMes(orderTrace.TraceId, "1", partProcess.Value.EndTime),
                                                    CreateTime = partProcess.Value.EndTime,
                                                    TraceId = orderTrace.TraceId,
                                                    BatchId = string.IsNullOrEmpty(batch) ? "" : batch,
                                                    Count = 1,
                                                    ProcessId = operations,
                                                    DataFrom = "德恒W03左右门槛线",
                                                });
                                            }

                                            // 更新工站表状态
                                            bool isOk = await orderDao.UpdateStationSaveStatus(partProcess.Key);
                                        }
                                    }
                                    else
                                    {
                                        if(processIds?.Count > 0)
                                        {
                                            // 判断有无末工序的已推送状态
                                            bool isSave = await orderDao.GetOverStationSaveStatus(processIds);

                                            if (isSave)
                                                // 更新OrderTrace推送状态
                                                await orderDao.UpDateOrderTraceSave(orderTrace.TraceId, orderTrace.OrderId);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Tools.ProduceLogTextError($"推送过站数据与投料数据失败，原因是{ex.Message}");
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Tools.ProduceLogTextError($"组装或者推送工厂Mes数据失败，原因是{ex.Message}");
                }
            }
        }
    }
}
